<?php
// inc/class/database.php
namespace smp;

use mysqli;
use smp\Base;

class Database extends Base {

	// Properties ->
	protected static $dbinfo = array();
	protected static $instance = false;
	protected static $errno, $error, $trace, $errorpage;
	protected static $readonly = array('error', 'errno', 'trace', 'readonly', 'secret', 'dbinfo', 'instance');
	protected static $secret = array('readonly', 'secret', 'dbinfo', 'instance');

	// getInstance ->
	public static function getInstance() {
		static::setTrace('getInstance');
		if(!static::$instance or !static::$instance instanceof mysqli) {
			if(!static::newInstance()) {
				return false;
			}
		}
	return static::$instance;
	}

	// close ->
	public static function close() {
		if(!static::$instance) { return; }
		if(static::$instance instanceof mysqli) {
			mysqli_close(static::$instance);
		}
		static::$instance = false;
	}

	// loadDBInfo ->
	protected static function loadDBInfo() {
		if(!$db = parse_ini_file(_base.'inc/secure/db.config.ini')) {
			return false;
		}
		static::$dbinfo = $db;
		unset($db);
	return true;
	}

	// newInstance ->
	protected static function newInstance() {
		static::setTrace('newInstance');
		if(!static::$dbinfo and !static::loadDBInfo()) {
			static::$errno = 1;
			static::$error = 'Unable to read database config!';
			static::$errorpage = 'err.mysql.config.htm';
		return false;
		}
		$db = @new mysqli(static::$dbinfo['host'], static::$dbinfo['user'], static::$dbinfo['pass'], static::$dbinfo['name']);
		if(mysqli_connect_errno()) { // -!
			static::$errno = mysqli_connect_errno();
			static::$error = mysqli_connect_error();
			static::$errorpage = 'err.mysql.connect.htm';
		return false;
		}
		static::$instance = $db;
		unset($db);
	return true;
	}

}